from datetime import datetime
from typing import List, Optional
from sqlalchemy import Column, Integer, String, Text, TIMESTAMP, Boolean, ForeignKey, Enum, BigInteger
from sqlalchemy.orm import relationship
from app.core.database import Base


class Conversation(Base):
    """用户会话表模型"""
    __tablename__ = "conversations"

    id = Column(String(36), primary_key=True, comment="会话ID（UUID）")
    user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, comment="用户ID")
    title = Column(String(200), nullable=False, default="新的聊天", comment="会话标题")
    created_at = Column(TIMESTAMP, default=datetime.utcnow, comment="创建时间")
    updated_at = Column(TIMESTAMP, default=datetime.utcnow, onupdate=datetime.utcnow, comment="最后更新时间")
    is_deleted = Column(Boolean, default=False, comment="是否已删除（软删除）")

    # 关系映射
    user = relationship("User", back_populates="conversations")
    messages = relationship("Message", back_populates="conversation", cascade="all, delete-orphan", order_by="Message.message_order")
    stats = relationship("ConversationStats", back_populates="conversation", uselist=False, cascade="all, delete-orphan")

    def __repr__(self):
        return f"<Conversation(id='{self.id}', user_id={self.user_id}, title='{self.title}')>"

    def to_dict(self) -> dict:
        """转换为字典格式"""
        return {
            "id": self.id,
            "user_id": self.user_id,
            "title": self.title,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
            "is_deleted": self.is_deleted,
            "message_count": len(self.messages) if self.messages else 0
        }


class Message(Base):
    """聊天消息表模型"""
    __tablename__ = "messages"

    id = Column(BigInteger, primary_key=True, autoincrement=True, comment="消息ID")
    conversation_id = Column(String(36), ForeignKey("conversations.id", ondelete="CASCADE"), nullable=False, comment="会话ID")
    sender = Column(Enum("user", "bot", "system", name="sender_type"), nullable=False, comment="发送者类型")
    content = Column(Text, nullable=False, comment="消息内容")
    created_at = Column(TIMESTAMP, default=datetime.utcnow, comment="创建时间")
    message_order = Column(Integer, nullable=False, comment="消息在会话中的顺序")

    # 关系映射
    conversation = relationship("Conversation", back_populates="messages")

    def __repr__(self):
        return f"<Message(id={self.id}, conversation_id='{self.conversation_id}', sender='{self.sender}')>"

    def to_dict(self) -> dict:
        """转换为字典格式"""
        return {
            "id": self.id,
            "conversation_id": self.conversation_id,
            "sender": self.sender,
            "content": self.content,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "message_order": self.message_order
        }


class ConversationStats(Base):
    """会话统计表模型"""
    __tablename__ = "conversation_stats"

    conversation_id = Column(String(36), ForeignKey("conversations.id", ondelete="CASCADE"), primary_key=True, comment="会话ID")
    message_count = Column(Integer, default=0, comment="消息总数")
    last_message_at = Column(TIMESTAMP, nullable=True, comment="最后一条消息时间")

    # 关系映射
    conversation = relationship("Conversation", back_populates="stats")

    def __repr__(self):
        return f"<ConversationStats(conversation_id='{self.conversation_id}', message_count={self.message_count})>"

    def to_dict(self) -> dict:
        """转换为字典格式"""
        return {
            "conversation_id": self.conversation_id,
            "message_count": self.message_count,
            "last_message_at": self.last_message_at.isoformat() if self.last_message_at else None
        }
